package units;

import pheromoneMap.PheromoneMap;
import pheromoneMap.PheromoneType;
import base.ProxyBot;
import base.WargusUnit;

public class SoldierUnit extends AntUnit {

	protected SoldierUnitState previous_state;
	public SoldierUnitState m_state;

	public SoldierUnit(ProxyBot proxyBot, PheromoneMap pheromoneMap,
			WargusUnit wargusUnit) {
		super(proxyBot, pheromoneMap, wargusUnit);
		
		this.m_state = SoldierUnitState.PATROL;
		this.previous_state = SoldierUnitState.PATROL;
	}

	public void updateState() {
		super.updateState();
		
		if( m_state == SoldierUnitState.PATROL ) {
			// If we sense an enemy or a death pheromone, go into the attack state
			if( pheromoneMap.getMagnitude(unit.getLocX(), unit.getLocY(), PheromoneType.DEATH ) >= 0.1
					|| pheromoneMap.getMagnitude(unit.getLocX(), unit.getLocY(), PheromoneType.ENEMY ) >= 0.1 ) {
				m_state = SoldierUnitState.ATTACK;
			}
		} else if( m_state == SoldierUnitState.ATTACK ) {
			// If we sense very high death and enemy, assume we're losing and flee.
			if( pheromoneMap.getMagnitude(unit.getLocX(), unit.getLocY(), PheromoneType.DEATH ) >= 2.0
					&& pheromoneMap.getMagnitude(unit.getLocX(), unit.getLocY(), PheromoneType.ENEMY ) >= 2.0
					&& pheromoneMap.getMagnitude(unit.getLocX(), unit.getLocY(), PheromoneType.MY_TERRITORY ) < 0.5 ) {
				m_state = SoldierUnitState.FLEE;
			}
			// If we sense very low enemy, assume the battle is over and go back to patrol.
			else if( pheromoneMap.getMagnitude(unit.getLocX(), unit.getLocY(), PheromoneType.ENEMY) < 0.1 ) {
				m_state = SoldierUnitState.PATROL;
			}
		} else if( m_state == SoldierUnitState.FLEE ) {
			if( pheromoneMap.getMagnitude(unit.getLocX(), unit.getLocY(), PheromoneType.ENEMY) < 0.1 ) {
				m_state = SoldierUnitState.PATROL;
			}
		}
	}
	
	public void move() {
		if( m_state == SoldierUnitState.PATROL ) {
			if (pheromoneMap.getMagnitude(unit.getLocX(), unit.getLocY(),
					PheromoneType.MY_TERRITORY) >= 0.5 ||
					pheromoneMap.getMagnitude(unit.getLocX(), unit.getLocY(),
					PheromoneType.MY_TERRITORY) < 0.1)
			{
				moveRandom();
			}
			else
			{
				moveTrail(PheromoneType.MY_TERRITORY);
			}
		}

		else if( m_state == SoldierUnitState.ATTACK ) {
			if (pheromoneMap.getMagnitude(unit.getLocX(), unit.getLocY(),
					PheromoneType.ENEMY) <= 0.1)
			{
				moveRandom();
			}
			else
			{
				moveTrailSticky(PheromoneType.ENEMY);
			}
		}

		else if( m_state == SoldierUnitState.FLEE ) {
			if (pheromoneMap.getMagnitude(unit.getLocX(), unit.getLocY(),
					PheromoneType.ENEMY) <= 0.1)
			{
				moveRandom();
			}
			else
			{
				moveTrailReverse(PheromoneType.ENEMY);
			}
		}
	}	
}
